/****************************************************************************
 *  This program is free software: you can redistribute it and/or modify    *
 *  it under the terms of the GNU General Public License as published by    *
 *  the Free Software Foundation, either version 3 of the License, or       *
 *  (at your option) any later version.                                     *
 *                                                                          *
 *  This program is distributed in the hope that it will be useful,         *
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of          *
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the           *
 *  GNU General Public License for more details.                            *
 *                                                                          *
 *  You should have received a copy of the GNU General Public License       *
 *  along with this program.  If not, see <http://www.gnu.org/licenses/>.   *
 *                                                                          *
 * ------------------------------------------------------------------------ *
 * This program is written by Dylan Taylor                                  *
 ****************************************************************************/
package gnometitlebarbuttonpositioning;

import java.awt.datatransfer.*;
import java.io.*;
import javax.swing.*;

public class Main extends javax.swing.JFrame {

    public DefaultListModel ordermodel = new DefaultListModel();
    public DefaultComboBoxModel sidemodel = new DefaultComboBoxModel();
    //The following is for easy internationalization. These strings should be modified in the "Bundle.properties" file instead of directly.
    public String minimize = java.util.ResourceBundle.getBundle("gnometitlebarbuttonpositioning/Bundle").getString("MINIMIZE");
    public String maximize = java.util.ResourceBundle.getBundle("gnometitlebarbuttonpositioning/Bundle").getString("MAXIMIZE");
    public String close = java.util.ResourceBundle.getBundle("gnometitlebarbuttonpositioning/Bundle").getString("CLOSE");
    public String left_side = java.util.ResourceBundle.getBundle("gnometitlebarbuttonpositioning/Bundle").getString("LEFT SIDE");
    public String right_side = java.util.ResourceBundle.getBundle("gnometitlebarbuttonpositioning/Bundle").getString("RIGHT SIDE");
    public String created_by = java.util.ResourceBundle.getBundle("gnometitlebarbuttonpositioning/Bundle").getString("CREATED BY");
    public String attempting = java.util.ResourceBundle.getBundle("gnometitlebarbuttonpositioning/Bundle").getString("ATTEMPTING TO RUN COMMAND:");
    public String sorry1 = java.util.ResourceBundle.getBundle("gnometitlebarbuttonpositioning/Bundle").getString("SORRY, I DON'T HAVE ENOUGH PERMISSIONS TO AUTOMATICALLY ADJUST YOUR TITLE BAR.");
    public String sorry2 = java.util.ResourceBundle.getBundle("gnometitlebarbuttonpositioning/Bundle").getString("TO MANUALLY APPLY THE CHANGES, RUN THIS COMMAND IN THE TERMINAL:");

    /** Creates new form Main */
    public Main() {
        if (ordermodel.isEmpty()) {
            ordermodel.addElement(minimize);
            ordermodel.addElement(maximize);
            ordermodel.addElement(close);
        }
        if (sidemodel.getSize() == 0) {
            sidemodel.addElement(right_side);
            sidemodel.addElement(left_side);
        }
        initComponents();
        order.setTransferHandler(new TransferHandler() {

            @Override
            public boolean canImport(TransferHandler.TransferSupport info) {
                if (!info.isDataFlavorSupported(DataFlavor.stringFlavor)) {
                    return false;
                }
                return true;
            }

            @Override
            public boolean importData(TransferHandler.TransferSupport info) {
                if (!info.isDrop()) {
                    return false;
                }
                if (!info.isDataFlavorSupported(DataFlavor.stringFlavor)) {
                    return false;
                }
                JList.DropLocation dl = (JList.DropLocation) info.getDropLocation();
                DefaultListModel listModel = (DefaultListModel) order.getModel();
                int index = dl.getIndex();
                boolean insert = dl.isInsert();
                String value = (String) listModel.getElementAt(index);
                Transferable t = info.getTransferable();
                String data;
                try {
                    data = (String) t.getTransferData(DataFlavor.stringFlavor);
                } catch (Exception e) {
                    return false;
                }
                // Checks if the data is acceptable
                if (data.equals(minimize) || (data.equals(maximize)) || (data.equals(close))) {
                    //Prevent Duplicate Items
                    if (listModel.contains(data)) {
                        if (insert) {
                            for (int rm = 0; rm < (listModel.getSize()); rm++) {
                                if (listModel.getElementAt(rm).toString().equals(data)) {
                                    listModel.remove(rm);
                                }
                            }
                            listModel.add(index, data);
                        }
                    }
                }
                return true;
            }

            @Override
            public int getSourceActions(JComponent c) {
                return COPY;
            }

            @Override
            protected Transferable createTransferable(JComponent c) {
                JList list = (JList) c;
                Object[] values = list.getSelectedValues();

                StringBuffer buff = new StringBuffer();

                for (int i = 0; i < values.length; i++) {
                    Object val = values[i];
                    buff.append(val == null ? "" : val.toString());
                    if (i != values.length - 1) {
                        buff.append("\n");
                    }
                }
                return new StringSelection(buff.toString());
            }
        });
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        topseparator = new javax.swing.JSeparator();
        positioninglabel = new javax.swing.JLabel();
        side = new javax.swing.JComboBox();
        orderlabel = new javax.swing.JLabel();
        ordercontainer = new javax.swing.JScrollPane();
        order = new javax.swing.JList();
        draganddroplabel = new javax.swing.JLabel();
        apply = new javax.swing.JButton();
        bottomseparator = new javax.swing.JSeparator();
        cancel = new javax.swing.JButton();
        credits = new javax.swing.JLabel();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        java.util.ResourceBundle bundle = java.util.ResourceBundle.getBundle("gnometitlebarbuttonpositioning/Bundle"); // NOI18N
        setTitle(bundle.getString("TITLE BAR BUTTON POSITIONING")); // NOI18N
        setCursor(new java.awt.Cursor(java.awt.Cursor.DEFAULT_CURSOR));
        setResizable(false);
        positioninglabel.setFont(new java.awt.Font("DejaVu Sans", 1, 13)); // NOI18N
        positioninglabel.setText(bundle.getString("BUTTON POSITIONING")); // NOI18N
        side.setModel(sidemodel);
        orderlabel.setFont(new java.awt.Font("DejaVu Sans", 1, 13)); // NOI18N
        orderlabel.setText(bundle.getString("ORDER OF THE BUTTONS")); // NOI18N
        order.setModel(ordermodel);
        order.setDragEnabled(true);
        order.setDropMode(javax.swing.DropMode.ON_OR_INSERT);
        ordercontainer.setViewportView(order);

        draganddroplabel.setText(bundle.getString("DRAG & DROP THE BUTTONS TO CHANGE THE ORDER!")); // NOI18N

        apply.setText(bundle.getString("APPLY")); // NOI18N
        apply.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                applyActionPerformed(evt);
            }
        });

        cancel.setText(bundle.getString("CANCEL")); // NOI18N
        cancel.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                cancelActionPerformed(evt);
            }
        });

        credits.setForeground(new java.awt.Color(196, 196, 196));
        credits.setText(bundle.getString("CREATED BY DYLAN TAYLOR")); // NOI18N

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(topseparator, javax.swing.GroupLayout.DEFAULT_SIZE, 332, Short.MAX_VALUE)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(positioninglabel)
                .addGap(18, 18, 18)
                .addComponent(side, javax.swing.GroupLayout.PREFERRED_SIZE, 146, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap())
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(orderlabel, javax.swing.GroupLayout.DEFAULT_SIZE, 308, Short.MAX_VALUE)
                .addContainerGap())
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(ordercontainer, javax.swing.GroupLayout.DEFAULT_SIZE, 308, Short.MAX_VALUE)
                .addContainerGap())
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(draganddroplabel, javax.swing.GroupLayout.DEFAULT_SIZE, 308, Short.MAX_VALUE)
                .addContainerGap())
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(credits, javax.swing.GroupLayout.DEFAULT_SIZE, 174, Short.MAX_VALUE)
                .addGap(18, 18, 18)
                .addComponent(cancel)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(apply)
                .addContainerGap())
            .addComponent(bottomseparator, javax.swing.GroupLayout.DEFAULT_SIZE, 332, Short.MAX_VALUE)
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(positioninglabel)
                    .addComponent(side, javax.swing.GroupLayout.DEFAULT_SIZE, 25, Short.MAX_VALUE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(topseparator, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(orderlabel)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(ordercontainer, javax.swing.GroupLayout.PREFERRED_SIZE, 80, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(draganddroplabel, javax.swing.GroupLayout.PREFERRED_SIZE, 21, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(bottomseparator, javax.swing.GroupLayout.PREFERRED_SIZE, 10, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
                    .addComponent(apply, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(cancel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(credits, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                .addContainerGap())
        );

        layout.linkSize(javax.swing.SwingConstants.VERTICAL, new java.awt.Component[] {positioninglabel, side});

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void applyActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_applyActionPerformed
        reposition();
    }//GEN-LAST:event_applyActionPerformed

    private void cancelActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cancelActionPerformed
        System.exit(0);
    }//GEN-LAST:event_cancelActionPerformed

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {

            public void run() {
                try { //first we attempt to set the look and feel to Gtk+
                    UIManager.setLookAndFeel("com.sun.java.swing.plaf.gtk.GTKLookAndFeel");
                } catch (Exception e) {
                    //leave the UI at system default
                }
                new Main().setVisible(true);
            }
        });
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton apply;
    private javax.swing.JSeparator bottomseparator;
    private javax.swing.JButton cancel;
    private javax.swing.JLabel credits;
    private javax.swing.JLabel draganddroplabel;
    private javax.swing.JList order;
    private javax.swing.JScrollPane ordercontainer;
    private javax.swing.JLabel orderlabel;
    private javax.swing.JLabel positioninglabel;
    private javax.swing.JComboBox side;
    private javax.swing.JSeparator topseparator;
    // End of variables declaration//GEN-END:variables

    @SuppressWarnings("empty-statement")
    private void reposition() {
        String arguments = "";
        if (side.getSelectedItem().equals(right_side)) {
            arguments = ":";
        }
        boolean invalid = false;
        for (int addbuttons = 0; addbuttons < ordermodel.getSize(); addbuttons++) {
            invalid = false;
            if (ordermodel.getElementAt(addbuttons).toString().equals(minimize)) {
                arguments = arguments + "minimize";
            } else if (ordermodel.getElementAt(addbuttons).toString().equals(maximize)) {
                arguments = arguments + "maximize";
            } else if (ordermodel.getElementAt(addbuttons).toString().equals(close)) {
                arguments = arguments + "close";
            } else {
                invalid = true;
            }
            if ((!invalid) && (addbuttons < (ordermodel.getSize() - 1))) {
                arguments = arguments + ",";
            }
        }
        String command[] = {"gconftool-2", "--set", "/apps/metacity/general/button_layout", "--type", "string", arguments};
        String commandrun = "gconftool-2 --set \"/apps/metacity/general/button_layout\" --type string \"" + arguments + "\"";
        //Now, once the command to run is built, try to run it.
        try {
            System.out.println(attempting + "\n" + commandrun);
            Runtime.getRuntime().exec(command);
        } catch (IOException ex) {
            JOptionPane.showMessageDialog(null, sorry1 + "\n" + sorry2 + "\n" + arguments);
        }
    }
}
